package pers.cz.logtail.annotation;

import pers.cz.exception.ErrorCode;
import pers.cz.exception.LogSaveException;
import pers.cz.log.LogUtils;
import pers.cz.logtail.config.RegeditTypeEnum;
import pers.cz.logtail.regedit.ServiceRegedit;
import pers.cz.util.AnnoManageUtil;
import pers.cz.util.DynamicEnumUtil;

import java.util.List;

/**
 * @program: JefLogTail
 * @description: 处理各种注册中心
 * @author: Cheng Zhi
 * @create: 2023-10-04 21:36
 **/
public class AutoRegistServiceManager {


    public final static String scanPackage = "pers.cz.logtail.regedit";

    /**
     * 注册枚举类
     */
    public void registe() {
        List<Class<?>> packageAnnos = AnnoManageUtil.getPackageAnno(scanPackage, AutoRegistService.class);
        for (Class<?> c : packageAnnos) {
            init(scanPackage, c);
        }
    }

    private void init(String basePackage, Class<?> clazz) {
        try {
            String className = clazz.getName();
            // 获取到的类全名需要去掉包名
            className = className.replaceAll(basePackage + ".","");
            // 默认截取去掉后七位（serviceRegedit）的剩余部分
            String nodeName = className.substring(0,className.length()-14);
            LogUtils.debug(nodeName + "注册成功！！！");
            // 进行注册
            registerEnum(nodeName, clazz);
        } catch (Exception e) {
            throw new LogSaveException(ErrorCode.SAVE_PLAN_NAME_IS_NULL_ERROR, e);
        }
    }
    private void registerEnum(String nodeName, Class nodeClass) {
        // 默认自动添加枚举
        addNodeEnum(nodeName.toUpperCase(), nodeName.toLowerCase(), nodeClass);
    }


    /**
     * 添加枚举
     * @param enumName 枚举名
     * @param code 枚举项1
     * @param nodeClass 枚举项2
     */
    private void addNodeEnum(String enumName, String code, Class<? extends ServiceRegedit> nodeClass) {
        DynamicEnumUtil.addEnum(RegeditTypeEnum.class, enumName, new Class<?>[]{String.class, Class.class}, new Object[]{code, nodeClass});
    }
}
